using System;
using System.Collections.Generic;
using System.Text;
using NBusiness.Query;

namespace NBusiness.Data.Providers.SqlServer.Query
{
    public class SqlColumn : SqlEvaluatable, IColumn
    {
        #region Member variables and properties
        private string _name;
        private string _alias;
        #endregion

        #region Constructors
        public SqlColumn(string name)
            : this(name, null, null)
        { }
        public SqlColumn(string name, ISource parent)
            : this(name, null, parent)
        { }
        public SqlColumn(string name, string alias)
            : this(name, alias, null)
        { }
        public SqlColumn(string name, string alias, ISource parent)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            _name = name;
            _alias = alias;
            _parent = parent;
        }
        #endregion

        #region IColumn Members

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string Alias
        {
            get { return _alias; }
            set { _alias = value; }
        }

        private ISource _parent;
        public ISource Parent
        {
            get { return _parent; }
            set { _parent = value; }
        }

        public IColumn As(string alias)
        {
            _alias = alias;
            return this;
        }

        #endregion

        #region IRelationalElement Members

        public override string ToSql()
        {
            return ToSql(new SqlQueryContext());
        }
        public override string ToSql(IQueryContext context)
        {
            StringBuilder builder = new StringBuilder();
            if (Parent != null)
            {
                SqlQueryContext sqlContext = context as SqlQueryContext;
                string alias = sqlContext.EnsureAlias(Parent);

                string title = alias;
                if (string.IsNullOrEmpty(alias) && 
                    sqlContext.AliasStyle == AliasAssignmentStyle.TableName &&
                    Parent is ITable)
                    title = (Parent as ITable).Name;

                if(!string.IsNullOrEmpty(title))
                    builder.Append("[" + title + "].");
            }
            builder.Append("[" + _name + "]");

            if (!string.IsNullOrEmpty(_alias))
                builder.Append(" AS [" + _alias + "]");
            

            return builder.ToString();
        }

        #endregion
    }
}
